<?php

namespace app\controller\api;

use app\util\ReturnCode;
use app\util\Sample;
use think\Response;
use think\Request;
use GuzzleHttp\Client;

class User extends Base
{
    public function logout()
    {
        $id = $this->request->post('id');
        $key = 'railway_token_' . $id;
        $key = md5($key);
        delCache($key);
        return $this->buildSuccess();
    }

    public function login(Request $request)
    {
        $code = $request->post('code');
        if (!$code) {
            return json(['error' => '缺少授权码'], 400);
        }
        $accessToken = $this->getDingTalkAccessToken();
        if (!$accessToken) {
            return json(['error' => '钉钉服务异常'], 500);
        }
        $url = "https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=".$accessToken;
        $client = new Client();
        $response = $client->post($url, [
            'json' => [
                'code' => $code
            ]
        ]);

        $data = json_decode($response->getBody(), true);
        if(!isset($data['errcode']) || $data['errcode'] || !isset($data['result'])){
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, $data['errmsg'] ?? '网络错误');
        }
        $userModel = new \app\model\User();
        $where = ['unionid' => $data['result']['unionid']];
        $userInfo = $userModel->where($where)->find();
        if(!$userInfo){
            $user_data = [
                'name' => $data['result']['name'],
                'avatar' => 'https://railway.sys.weilianyun.vip/default_avatar.png',
                'sys_level' => $data['result']['sys_level'],
                'unionid' => $data['result']['unionid'],
                'dingtalk_userid' => $data['result']['userid'],
                'sys' => $data['result']['sys'] ? 1 : 0,
                'create_time' => time()
            ];
            $id = $userModel->insertGetId($user_data);
            $userInfo = $userModel->where(['id' => $id])->find();
        }
        $userInfo = $userInfo->toArray();
        $key = 'railway_token_' . $userInfo['id'];
        $key = md5($key);
        setCache($key,$userInfo,86400);
        $arr = [
            'user_info' => $userInfo,
            'token' => $key
        ];
        return $this->buildSuccess($arr);
    }

    public function userInfo()
    {
        $id = $this->request->get('id');
        $model = new \app\model\User();
        $where = ['id' => $id];
        $data = $model->where($where)
            ->find()
            ->toArray();
        return $this->buildSuccess($data);
    }

    public function upload(): Response {
        $path = '/upload/' . date('Ymd', time()) . '/';
        $name = $_FILES['file']['name'];
        $tmp_name = $_FILES['file']['tmp_name'];
        $error = $_FILES['file']['error'];
        //过滤错误
        if ($error) {
            switch ($error) {
                case 1:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小';
                    break;
                case 2:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小';
                    break;
                case 3:
                    $error_message = '文件只被部分上传';
                    break;
                case 4:
                    $error_message = '文件不能为空';
                    break;
                default:
                    $error_message = '未知错误';
            }
            die($error_message);
        }
        $arr_name = explode('.', $name);
        $hz = array_pop($arr_name);
        $new_name = md5(time() . uniqid()) . '.' . $hz;
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $path)) {
            mkdir($_SERVER['DOCUMENT_ROOT'] . $path, 0755, true);
        }
        if (move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT'] . $path . $new_name)) {
            return $this->buildSuccess([
                'fileName' => $new_name,
                'fileUrl'  => $this->request->domain() . $path . $new_name
            ]);
        } else {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, '文件上传失败');
        }
    }

    private function getDingTalkAccessToken()
    {
        return Sample::main();
    }

    public function list()
    {
        $model = new \app\model\User();
        $data = $model->field('id,name')->select()->toArray();
        return $this->buildSuccess($data);
    }
}
